<template>
  <div class="user-profile-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 用户信息展示与编辑 -->
    <div v-else-if="userInfo" class="user-info-section">
      <h2>用户信息</h2>

      <!-- 显示用户ID -->
      <p><strong>用户ID：</strong>{{ userInfo.ID }}</p>

      <!-- 显示用户名 -->
      <p><strong>用户名：</strong>{{ userInfo.username }}</p>

      <!-- 显示创建时间 -->
      <p><strong>创建时间：</strong>{{ userInfo.CreatedAt }}</p>

      <!-- 显示用户等级及权限说明 -->
      <p><strong>用户等级：</strong>{{ userInfo.level }}</p>
      <p class="permission-desc">
        <strong>权限说明：</strong>
        {{ permissionDescription }}
      </p>

      <!-- 编辑用户信息 -->
      <div class="edit-section">
        <label for="birthday">生日：</label>
        <input id="birthday" v-model="userInfo.birthday" />

        <label for="gender">性别：</label>
        <input id="gender" v-model="userInfo.gender" />

        <label for="signature">个性签名：</label>
        <input id="signature" v-model="userInfo.signature" />
      </div>

      <!-- 保存按钮 -->
      <el-button type="success" @click="saveUserInfo">保存更改</el-button>

      <!-- 头像上传 -->
      <div class="avatar-section">
        <h3>上传头像</h3>
        <img :src="avatarUrl || 'default-avatar.png'" alt="当前头像" width="100" />
        <input type="file" accept="image/*" @change="uploadAvatar" />
        <p v-if="uploadStatus" class="upload-status">{{ uploadStatus }}</p>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-else class="error-message">
      无法加载用户信息，请检查登录状态。
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import axios from '../axios'

// 定义 User 接口（与后端接口一致）
interface User {
  ID: number
  CreatedAt: string
  UpdatedAt: string
  DeletedAt: string | null
  username: string
  password: string
  avatar: string
  birthday: string
  gender: string
  signature: string
  level: number
  exp: number
}

const userInfo = ref<User | null>(null)
const loading = ref(true)
const avatarUrl = ref<string | null>(null)
const uploadStatus = ref('')
const defaultAvatar = 'default-avatar.png'

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get<User>('/users/me')
    userInfo.value = response.data
    avatarUrl.value = response.data.avatar || defaultAvatar
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = null
  } finally {
    loading.value = false
  }
}

// 保存用户信息到后端（仅发送允许修改的字段）
const saveUserInfo = async () => {
  if (!userInfo.value) return
  const { birthday, gender, signature } = userInfo.value
  try {
    await axios.put('/users/me/info', { birthday, gender, signature })
    alert('信息更新成功！')
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试。')
  }
}

// 上传头像
const uploadAvatar = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  const formData = new FormData()
  formData.append('avatar', file)

  try {
    const response = await axios.post('/users/me/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    avatarUrl.value = response.data.avatarUrl
    uploadStatus.value = '上传成功'
  } catch (error) {
    console.error('上传失败:', error)
    uploadStatus.value = '上传失败，请重试。'
  }
}

// 根据等级显示权限说明
const permissionDescription = computed(() => {
  if (!userInfo.value) return ''
  switch (userInfo.value.level) {
    case 1:
      return '仅可评论'
    case 2:
      return '可以发布帖子，编辑已发布的帖子'
    case 3:
      return '允许上传头像'
    case 4:
      return 'Super User：可以删除任意用户的帖子'
    default:
      return '未知等级'
  }
})

onMounted(() => {
  fetchUserInfo()
})
</script>
<style scoped>
.user-profile-container {
  max-width: 600px;
  margin: 60px auto;
  padding: 40px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  text-align: left;
}

.user-info-section h2 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #2c3e50;
}

.user-info-section p {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 10px;
}

.permission-desc {
  color: #7f8c8d;
  font-style: italic;
  margin-top: 8px;
}

.edit-section {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.edit-section label {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
}

.edit-section input {
  width: 100%;
  padding: 12px 14px;
  font-size: 15px;
  border: 1px solid #bbb;
  border-radius: 6px;
  transition: border-color 0.3s ease;
}

.edit-section input:focus {
  border-color: #409EFF;
  outline: none;
}

.avatar-section {
  margin-top: 30px;
}

.avatar-section img {
  margin-top: 12px;
  border-radius: 50%;
  border: 2px solid #ddd;
}

.upload-status {
  color: green;
  font-weight: bold;
  margin-top: 8px;
}
.el-button--success {
  margin-top: 24px;
  padding: 14px 24px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #4caf50;
}

.loading,
.error-message {
  font-size: 18px;
  text-align: center;
  padding: 40px;
  color: #666;
}

</style>